<?php

namespace App\Http\Controllers\Api;

use App\Film;
use App\Project;
use App\Session;
use App\ZhuanziFilm;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ProjectController extends BaseController
{
    public $user;
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->user = $this->is_login($request);
    }

    /**
     * @param Request $request
     * 手动获取影片信息
     */
    public function film_info_query(Request $request){

        if (!$start_date=trim($request->start_date)){
            return error('开始时间缺失');
        }

        if (!$end_date = trim($request->end_date)){
            return error('结束时间缺失');
        }

        if (date('Y-m-d',strtotime($start_date))!=$start_date){
            return error('开始时间格式错误');
        }

        if (date('Y-m-d',strtotime($end_date))!=$end_date){
            return error('结束时间格式错误');
        }

        $str = http_build_query([
            'start_date'=>$start_date,
            'end_date'=>$end_date
        ]);

        $res = curl($_ENV['SERVER_D'].'/FilmInfoQuery',$str,false);
        
        $res = json_decode($res,true);
        if ($res&&$res['return_value']==0){
            logs($this->user,'手动获取专资影片'.json_encode($res).'成功');
            return success($res,'获取影片成功');
        }else{
            logs($this->user,'手动获取专资影片失败');
            return error('获取影片失败');
        }
    }

    /**
     * @param Request $request
     * 影片列表
     */
    public function index(Request $request){

        if (!$this->user['data']->can('local_film')){
            return error('NoPermission');
        }

        $films = \DB::table('projects')->orderBy('id','desc');
        $name = trim($request->input('name'));
        $code = trim($request->input('code'));
        $publish_date = trim($request->input('publish_date'));
        $publish_end_date = trim($request->input('publish_end_date'));
        $images = trim($request->input('images'));
        $frames = trim($request->input('frames'));
        $languages = trim($request->input('languages'));
        $lowest = trim($request->input('lowest'));
        $name&&$films->where('name','like','%'.$name.'%');
        $code&&$films->where('code','like','%'.$code.'%');
        $publish_date&&$publish_end_date&&$films->whereBetween('publish_date',[$publish_date,$publish_end_date]);
        $images&&$films->where('image_types','like','%,'.$images.'%');
        $frames&&$films->where('frame_types','like','%,'.$frames.'%');
        $languages&&$films->where('languages','like','%,'.$languages.'%');
        $lowest&&$films->where('lowest','=',$lowest);
        $data=$films->paginate(15);
        return success($data,'查询成功');
    }

    /**
     * @param Request $request
     * 影片信息
     */
    public function info(Request $request){

        if (!$id=trim($request->input('id'))){
            return error('影片id缺失');
        }

        $film = Film::where(['status'=>1])->find($id);
        if(!$film){
            return error('影片不存在');
        }else{
            return success($film,'查询成功');
        }
    }

    /**
     * @param Request $request
     * 查询专资影片库
     */
    public function zhuanzi_list(Request $request){
        $zhuanzi = \DB::table('zhuanzi_films');
        $name = trim($request->input('name'));
        $code = trim($request->input('code'));
        $publish_date = trim($request->input('publish_date'));
        $publish_end_date = trim($request->input('publish_end_date'));
        $name&&$zhuanzi->where('name','like','%'.$name.'%');
        $code&&$zhuanzi->where('code','like','%'.$code.'%');
        $publish_date&&$publish_end_date&&$zhuanzi->whereBetween('publish_date',[$publish_date,$publish_end_date]);
        $data = $zhuanzi->paginate(15);
        return success($data,'查询成功');
    }

    /**
     * 添加本地影片
     */
    public function add_film(Request $request){

        if (!$this->user['data']->can('zhuanzi_film')){
            return error('NoPermission');
        }

        if (!$film_tab = trim($request->input('film_tab'))){
            return error('影片特征码缺失');
        }

        if (!$name = trim($request->input('name'))){
            return error('影片名称必填');
        }

        if (!$duration = trim($request->input('duration'))){
            return error('影片时长必填');
        }

//        if ($duration%300!=0){
//            return error('请输入影片时长为5的倍数');
//        }

        if (!$publish_date =trim($request->input('publish_date'))){
            return error('公映日期必填');
        }

        if (!$publisher = trim($request->input('publisher'))){
            return error('发行商必填');
        }

        if (!$producer = trim($request->input('producer'))){
            return error('制作人必填');
        }

        if (!$director = trim($request->input('director'))){
            return error('导演必填');
        }

        if (!$cast = trim($request->input('cast'))){
            return error('演员必填');
        }

        if (!$introduction = trim($request->input('introduction'))){
            return error('简介必填');
        }

        if (!$languages = trim($request->input('languages'))){
            return error('语言信息必填');
        }

        if (!$images = trim($request->input('images'))){
            return error('画面类型必填');
        }

        if (!$frames = trim($request->input('frames'))){
            return error('屏幕制式必填');

        }
        if (!$publish_end_date = trim($request->input('publish_end_date'))){
            return error('下映日期必填');
        }
        if (!$lowest_price = trim($request->input('lowest_price'))){
            return error('最低票价必填');
        }
        if (!$share_proportion = trim($request->input('share_proportion'))){
            return error('分账比必填');
        }
        $lowest_price = json_decode($lowest_price,true);
        $share_proportion = json_decode($share_proportion,true);
        $images = json_decode($images,true);
        $frames = json_decode($frames,true);


        /**********************存在project_id***************************/
        $project_id = ZhuanziFilm::where(['film_tab'=>$film_tab])->where('project_id','!=','')->value('project_id');
        if ($project_id){
            $project = Project::find($project_id);
            /***********************存在于本地影片库**************************/
            $project_film = Film::where(['project_id'=>$project_id])->get();
            if ($project_film->count()>0){
                $data = [];
                foreach ($project_film as $val){
                    $up =[];
                    $up['id'] = $val->id;
                    $up['languages'] = $languages;
                    $up['duration'] = $duration;
                    $up['publish_date'] = $publish_date;
                    $up['publisher'] = $publisher;
                    $up['producer'] = $producer;
                    $up['director'] = $director;
                    $up['cast'] = $cast;
                    $up['introduction'] = $introduction;
                    $up['publish_end_date'] = $publish_end_date;
                    $up['image_types'] = array_get($images,$val->code);
                    $up['frame_types'] = array_get($frames,$val->code);
                    $up['lowest_price'] = array_get($lowest_price,$val->code);
                    $up['share_proportion'] = array_get($share_proportion,$val->code);
                    $data[] = $up;
                }
                $res_zhuanzi_update = updateBatch('films',$data);
            }
        }else{
            /************************不存在project_id***********************/
            $project = new Project();
        }

        $codes = ZhuanziFilm::where(['film_tab'=>$film_tab])->pluck('code');
        $image_types =[];
        foreach ($codes as $val){
            $image_types[] = array_get($images,$val);
            $frame_types[] = array_get($frames,$val);
        }
        $image_types = implode(',',$image_types);
        $image_types = explode(',',$image_types);
        $frame_types = implode(',',$frame_types);
        $frame_types = explode(',',$frame_types);

        $project->name = $name;
        $project->languages = ','.$languages;
        $project->image_types = ','.implode(',',array_unique($image_types));
        $project->frame_types = ','.implode(',',array_unique($frame_types));
        $project->duration = $duration;
        $project->publish_date = $publish_date;
        $project->publisher = $publisher;
        $project->producer = $producer;
        $project->director = $director;
        $project->cast = $cast;
        $project->introduction = $introduction;
        $project->publish_end_date = $publish_end_date;
        $project->film_tab = $film_tab;
        $res_project = $project->save();

        /*********************未存在于本地影片库***************************/
        $zhuanzi_unlocal_film = ZhuanziFilm::where(['film_tab'=>$film_tab,'status'=>1])->get();
        if ($zhuanzi_unlocal_film->count()>0){
            $data = [];
            foreach ($zhuanzi_unlocal_film as $val){
                $info = [];
                $info['code'] = $val->code;
                $info['name'] = $info['display_name']=$val->name;
                $info['version'] = $val->version;
                $info['languages'] = $languages;
                $info['image_types'] = array_get($images,$val->code);
                $info['frame_types'] = array_get($frames,$val->code);
                $info['duration'] = $duration;
                $info['publish_date'] = $publish_date;
                $info['publisher'] = $publisher;
                $info['producer'] = $producer;
                $info['director'] = $director;
                $info['cast'] = $cast;
                $info['introduction'] = $introduction;
                $info['publish_end_date'] = $publish_end_date;
                $info['lowest_price'] = array_get($lowest_price,$val->code);
                $info['share_proportion'] = array_get($share_proportion,$val->code);
                $info['project_id'] = $project->id;
                $data[] = $info;
            }
            $res_films = \DB::table('films')->insert($data);
        }

        $res_zhuanzi_status = ZhuanziFilm::where('film_tab','=',$film_tab)->update(['status'=>2,'project_id'=>$project->id]);
        if ($res_project&&$res_zhuanzi_status){
            return success($project,'添加成功');
        }
        return error('添加失败');

    }

    /**
     * @param Request $request
     * 获取项目详情
     */
    public function get_project_info(Request $request){

        if (!$this->user['data']->can('local_film')){
            return error('NoPermission');
        }

        if (!$film_tab = trim($request->input('film_tab'))){
            return error('影片特征码缺失');
        }
        $zhuanzi_info = ZhuanziFilm::where(['film_tab'=>$film_tab])->get();
        if ($zhuanzi_info->count()==0){
            return error('影片特征码不存在');
        }
        $project_id = ZhuanziFilm::where(['film_tab'=>$film_tab])->where('project_id','!=','')->value('project_id');
        $base_info = [];
        $images = [];
        $frames = [];
        $share_proportion = [];
        $lowest_price = [];
        if ($project_id){
            $project_info = Project::find($project_id);
            $share_proportion = Film::where(['project_id'=>$project_id])->pluck('share_proportion','code');
            $lowest_price = Film::where(['project_id'=>$project_id])->pluck('lowest_price','code');
            $base_info['name'] = $project_info['name'];
            $base_info['publish_date'] = $project_info['publish_date'];
            $base_info['publish_end_date'] = $project_info['publish_end_date'];
            $base_info['publisher'] = $project_info['publisher'];
            $base_info['producer'] = $project_info['producer'];
            $base_info['director'] = $project_info['director'];
            $base_info['duration'] = $project_info['duration'];
            $base_info['cast'] = $project_info['cast'];
            $base_info['introduction'] = $project_info['introduction'];
            $base_info['languages'] = $project_info['languages'];
            $image = explode(',',$project_info['image_types']);
            $frame = explode(',',$project_info['frame_types']);
            $images = array_merge($images,$image);
            $frames = array_merge($frames,$frame);
        }else{
            $zhuanzi_info = $zhuanzi_info->toArray();
            $base_info['name'] = $base_info['publish_end_date'] = $base_info['languages'] ='';
            $base_info['publish_date'] = $zhuanzi_info[0]['publish_date'];
            $base_info['publisher'] = $zhuanzi_info[0]['publisher'];
            $base_info['producer'] = $zhuanzi_info[0]['producer'];
            $base_info['director'] = $zhuanzi_info[0]['director'];
            $base_info['duration'] = $zhuanzi_info[0]['duration'];
            $base_info['cast'] = $zhuanzi_info[0]['cast'];
            $base_info['introduction'] = $zhuanzi_info[0]['introduction'];
        }

        $base_info['film_list'] = [];
        foreach ($zhuanzi_info as $val){
            $film_info = [];
            $film_info['name'] = $val['name'];
            $film_info['code'] = $val['code'];
            $film_info['share_proportion'] = array_get($share_proportion,$val['code']);
            $film_info['lowest_price'] = array_get($lowest_price,$val['code']);
            $film_info['code'] = $val['code'];
            $code = $val['code'];
            $val = substr($code,7,1);
            switch ($val){
                case 1:
                    $images[] = $film_info['image'] = 1;
                    $frames[] = $film_info['frame'] = 3;
                    break;
                case 2:
                    $images[] = $film_info['image'] = 2;
                    $frames[] = $film_info['frame'] = 3;
                    break;
                case 3:
                    $images[] = $film_info['image'] = 1;
                    $frames[] = $film_info['frame'] = 1;
                    break;
                case 4:
                    $images[] = $film_info['image'] = 2;
                    $frames[] = $film_info['frame'] = 1;
                    break;
                case 8:
                    $images[] = $film_info['image'] = 1;
                    $frames[] = $film_info['frame'] = 2;
                    break;
                case 9:
                    $images[] = $film_info['image'] = 2;
                    $frames[] = $film_info['frame'] = 2;
                    break;
                default :
                    $images[] = $film_info['image'] = 1;
                    $frames[] = $film_info['frame'] = 3;
            }

            $base_info['film_list'][] = $film_info;
        }

        $base_info['images'] = implode(',',array_filter(array_unique($images)));
        $base_info['frames'] = implode(',',array_filter(array_unique($frames)));
        return success($base_info,'查询成功');
    }



    /**
     * 删除影片
     */
    public function delete_film(Request $request){

        if (!$this->user['data']->can('local_film')){
            return error('NoPermission');
        }

        if (!$id = trim($request->input('id'))){
            return error('ID必填');
        }
        $project_info = Project::find($id);
        if (!$project_info){
            return error('影片不存在');
        }
        $count = Session::where(['project_id'=>$id])->count();
        if ($count>0){
            return error('排片中已存在该影片,不可删除');
        }
        $res_delete_project = $project_info->delete();
        $res_delete_films = Film::where(['project_id'=>$id])->delete();
        $res_update_zhuanzi = ZhuanziFilm::where(['project_id'=>$id])->update(['status'=>1,'project_id'=>null]);
        \DB::beginTransaction();
        try{
            if ($res_delete_films&&$res_delete_project&&$res_update_zhuanzi){
                \DB::commit();
                logs($this->user,'删除本地影片'.$project_info->name.'成功');
                return success('','删除影片成功');
            }
        }catch (\Exception $e){
            \DB::rollBack();
            logs($this->user,'删除本地影片'.$project_info->name.'失败');
            return error('删除影片失败');
        }
    }



}
